package com.ruoyi.flowable.listener;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.SysCopy;
import com.ruoyi.system.service.ISysCopyService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.common.engine.api.delegate.Expression;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.stereotype.Component;

/**
 * 抄送任务监听器
 *
 * @author Tony
 * @date 2023/3/17 10:02
 */
@Slf4j
@Component
public class FlowCopyTaskListener implements TaskListener {

    /**
     * 抄送人员id集合
     */
    private Expression userIds;

    @Override
    public void notify(DelegateTask delegateTask) {
        log.info("抄送任务监听器,{}", userIds.getExpressionText());
        // 将抄送信息分别插入到数据库中
        String expressionText = userIds.getExpressionText();
        if (StringUtils.isNotBlank(expressionText)) {
            // 从 Spring 容器中获取相关服务
            RepositoryService repositoryService = SpringUtils.getBean(RepositoryService.class);
            ISysCopyService sysCopyService = SpringUtils.getBean(ISysCopyService.class);
            ISysUserService sysUserService = SpringUtils.getBean(ISysUserService.class);

            // 获取流程定义信息
            ProcessDefinition pd = repositoryService.createProcessDefinitionQuery()
                    .processDefinitionId(delegateTask.getProcessDefinitionId())
                    .singleResult();

            // 获取任务发起人信息
            SysUser startUser = sysUserService.selectUserById(Long.parseLong(delegateTask.getAssignee()));

            // 构造 SysCopy 对象
            SysCopy sysCopy = new SysCopy();
            sysCopy.setProcInsId(delegateTask.getProcessInstanceId());
            sysCopy.setDeployId(pd.getDeploymentId());
            sysCopy.setProcName(pd.getName());
            sysCopy.setTaskId(delegateTask.getId());
            sysCopy.setTaskName(delegateTask.getName());
            sysCopy.setSendUserId(startUser.getUserId());
            sysCopy.setSendUserName(startUser.getNickName());
            sysCopy.setStatus(0);

            List<String> userIdList = Arrays.asList(expressionText.split(","));
            userIdList.forEach(userId -> {
                sysCopy.setReceiveUserId(Long.parseLong(userId));
                sysCopyService.insertSysCopy(sysCopy);
            });
        }
    }
}
